import {
	DesktopOutlined,
	PieChartOutlined,
	UserOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom'

type MenuItem = Required<MenuProps>['items'][number];

const items: MenuItem[] = [
    {
        label: 'Option 1',
        key: '/Page1',
        icon: <PieChartOutlined />
    },
    {
        label: 'Option 2',
        key: '/Page2',
        icon: <DesktopOutlined />
    },
    {
        label: 'User',
        key: 'Page3',
        icon: <UserOutlined />,
        children: [
            {
                label: 'Tom',
                key: '/page3/page301',
            },
            {
                label: 'Bill',
                key: '4',
            },
            {
                label: 'Alex',
                key: '5',
            }
        ]
    },
    {
        label: 'User2',
        key: 'sub2',
        icon: <UserOutlined />,
        children: [
            {
                label: 'Tom2',
                key: '31',
            },
            {
                label: 'Bill2',
                key: '41',
            },
            {
                label: 'Alex2',
                key: '51',
            }
        ]
    }
]

const Comp: React.FC = () => {
    const navigateTo = useNavigate();
    const currentPage = useLocation();
    
    const menuClick = (e: { key: string }) => {
        // 路由跳转 （编程式导航)
        navigateTo(e.key)
        
        
    }
    // console.log(currentPage);

    let firstOpenKey:string = '';

    function findKey (obj:{key:string | undefined}) {
        return obj.key === currentPage.pathname;
    }

    for (let i = 0; i < items.length; i++) {
        if (items[i]!['children'] && items[i]!['children'].length && items[i]!['children'].find(findKey)) {
            firstOpenKey = items[i]!.key as string;
            break;
        }
        
    }
    
    const [openKeys, setOpenkeys] = useState([firstOpenKey]);
    
    const handleChange = (keys: string[]) => {
        setOpenkeys([keys[keys.length - 1]]);
    }

    return (
        <Menu theme="dark"
        // 当前选中项样式
            defaultSelectedKeys={[currentPage.pathname]}
            mode="inline"
            items={items}
            onClick={menuClick}
            onOpenChange={handleChange}
            // 当前菜单展开项
            openKeys={openKeys}
        />
    )
}
export default Comp;